home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / 3d_lib.zip / DP.C < prev    next >
C/C++ Source or Header  |  1990-12-09  |  2KB  |  70 lines

  1. /* Calculate dot product
  2.  
  3.    Copyright (c) 1988 by Gus O'Donnell
  4.  
  5.    Revision history:
  6.  
  7.    Version 1.00         February 29, 1988       As released.
  8.  
  9.    Version 1.01         March 20, 1988          Created libraries for all
  10.                                                 memory models
  11.  
  12. */
  13. #include "3d.h"
  14. #include <float.h>
  15. #include <math.h>
  16. #include <stdio.h>
  17.  
  18. void    normalize (VECTOR this_vec)
  19.  
  20. /* Normalize a vector to unit magnitude.  Calculate the magnitude as:
  21.  
  22.                magnitude = sqrt ( x^2 + y^2 + z^2 )
  23.  
  24. Normalize the vector by dividing each coordinate by the magnitude.
  25.  
  26. FOR loops are used to maintain generality--any dimension vector may
  27. be normalized by changing DIM. */
  28.  
  29. {
  30.     double mag;
  31.     int count;
  32.  
  33.     mag = 0.0;
  34.     for (count = 0; count < DIM; count++)
  35.         mag = mag + (this_vec [count] * this_vec [count]);
  36.     mag = sqrt(mag);
  37.     for (count = 0; count < DIM; count++)
  38.         this_vec [count] = this_vec [count]/mag;
  39. }
  40.  
  41. double  dot_prod (VECTOR vec1, VECTOR vec2)
  42.  
  43. /* Calculate the cosine of the angle between two vectors.  First, normalize
  44. the vectors, then calculate the dot product as:
  45.  
  46.              dot product = (x1 * x2) + (y1 * y2) + (z1 * z2)
  47.  
  48. */
  49.  
  50. {
  51.     double COSINE;
  52.     int count;
  53.     VECTOR tvec1,tvec2;   /* Temporary storage is used to avoid changing
  54.                              the arguments passed to the function. */
  55.  
  56.     for (count = 0; count < DIM; count++)  /* Copy arguments to temporary */
  57.     {                                      /* storage. */
  58.         tvec1 [count] = vec1 [count];
  59.         tvec2 [count] = vec2 [count];
  60.     }
  61.     normalize (tvec1);
  62.     normalize (tvec2);
  63.     COSINE = 0.0;
  64.  
  65.     for (count = 0; count < DIM; count++)
  66.         COSINE = COSINE + tvec1 [count] * tvec2 [count];
  67.     return (COSINE);
  68. }
  69.  
  70.